package com.cs342.g4.memaps;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import basicClasses.LoginObject;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class CreateAcct extends Activity {

	private View mCreateFormView;
	private View mCreateStatusView;
	private TextView mCreateStatusMessageView;
	private EditText mEmailView;
	private EditText mPasswordView;

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActionBar ab = getActionBar(); ab.setDisplayShowTitleEnabled(false); 
		setContentView(R.layout.activity_create_acct);

		final Button create = (Button) findViewById(R.id.createAcct);
		final Button cancel = (Button) findViewById(R.id.cancelCreate);

		Bundle b = getIntent().getExtras();
		String email = b.getString("mEmail");
		String password = b.getString("mPassword");
		final EditText emailCreate = (EditText) findViewById(R.id.emailCreate);
		final EditText passwordCreate = (EditText) findViewById(R.id.passwordCreate);
		emailCreate.setText(email);
		passwordCreate.setText(password);
		final EditText confirmPassword = (EditText) findViewById(R.id.confirmPassword);
		confirmPassword.requestFocus();

		mCreateFormView = findViewById(R.id.create_form);
		mCreateStatusView = findViewById(R.id.creating_status);
		mCreateStatusMessageView = (TextView) findViewById(R.id.creating_status_message);

		create.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				String e = emailCreate.getText().toString();
				String p1 = passwordCreate.getText().toString();
				String p2 = confirmPassword.getText().toString();
				LoginObject loginO = new LoginObject(e,p1);

				if(p1.equals(p2)){
					try{
						mCreateStatusMessageView.setText("Creating Account..");
						showProgress(true);
						new createNewAccountTask().execute(loginO);

					} catch (Exception ex){
						System.out.println(ex);
					}

				}else{
					mPasswordView = (EditText) findViewById(R.id.confirmPassword);
					mPasswordView.setError("Passwords Don't Match");
					mPasswordView.requestFocus();
				}

			}
		});

		cancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent login = new Intent(CreateAcct.this, LoginActivity.class);
				startActivity(login);
				finish();
			}
		});

	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);
			mCreateStatusView.setVisibility(View.VISIBLE);
			mCreateStatusView.animate().setDuration(shortAnimTime)
			.alpha(show ? 1 : 0)
			.setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					mCreateStatusView.setVisibility(show ? View.VISIBLE
							: View.GONE);
				}
			});

			mCreateFormView.setVisibility(View.VISIBLE);
			mCreateFormView.animate().setDuration(shortAnimTime)
			.alpha(show ? 0 : 1)
			.setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					mCreateFormView.setVisibility(show ? View.GONE
							: View.VISIBLE);
				}
			});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mCreateStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mCreateFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	public class createNewAccountTask extends AsyncTask<LoginObject, Void, String> {

		@Override
		protected String doInBackground(LoginObject... params) {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://softeng.cs.uwosh.edu/students/cs342g4/sign_up.php");
			String resp = "";
			try
			{
				// Convert the login object to XML
				XStream xstream = new XStream(new DomDriver("UTF-8"));
				xstream.alias("Login", LoginObject.class);
				String xml = xstream.toXML(params[0]);

				// Pass the XML as a StringEntity
				StringEntity se = new StringEntity(xml, HTTP.UTF_8);
				se.setContentType("text/xml");
				httppost.setEntity(se);
				HttpResponse httpresponse = httpclient.execute(httppost);
				HttpEntity resEntity = httpresponse.getEntity();
				resp = EntityUtils.toString(resEntity);
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return resp;
		}

		@Override
		protected void onPostExecute(String result){
			showProgress(false);
			if(result.equals("true")){
				Intent main = new Intent(CreateAcct.this, MainActivity.class);
				startActivity(main);
				finish();
			}
			else if(result.equals("false")){
				mEmailView = (EditText) findViewById(R.id.emailCreate);
				mEmailView.setError("Username Already Exists");
				mEmailView.requestFocus();
			}

		}

	}

	@Override	
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//DONT WANT THIS TO DISPLAY 
		//getMenuInflater().inflate(R.menu.activity_create_acct, menu);
		return true;
	}

}
